package com.future.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.future.domain.Manager;
import com.future.domain.Student;
import com.future.domain.UserRole;
import com.future.dto.*;
import com.future.domain.Userinfo;
import com.future.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Auther: 田坑坑
 * @Date: 2022/6/13 14:55
 * @Description: 用户控制层
 */

@RestController
@RequestMapping("user")
public class UserInfoController {

    @Autowired
    LoginService loginService;

    @Autowired
    UserinfoService userinfoService;

    @Autowired
    StudentService  studentService;

    @Autowired
    ManagerService  managerService;

    @Autowired
    UserRoleService   userRoleService;




    //修改用户资料
    @PostMapping("changeUser")
    public MsgDto changeUser(@RequestBody Userinfo userinfo){

        //  1.判断该用户的身份
        List<LoginDto> userRoleList  =  this.loginService.updateSelect(userinfo.getUserid());
        String  role   =   userRoleList.get(0).getRoleName();

        System.out.println(role);

        // 去禁用
        if(userinfo.getStatus().equals("禁用")){

            //2.该用户为学生
            if(role.equals("学生")){

                //查询 学生表 ，查看寄宿状态,如果该学生为是寄宿状态,则提示无法禁用该用户
                UserRoleStatusDto  userRoleStatusDto  =  this.userinfoService.findRoleStatus(userinfo.getUserid());

                if(userRoleStatusDto.getStudentStatus().equals("是")){
                    return  new MsgDto(false,"该学生为是寄宿状态,不可禁用");
                }else {

                    //将该学生用户禁用
                    this.userinfoService.updateById(userinfo);

                    return  new MsgDto(true,"可禁用");
                }



            }else{
                // 用户为宿管 ，查看是否有管理的宿舍,如果有,则提示无法禁用该用户




                //2.查看该宿管是否 有管理的宿舍
                List<ManagerForRoomDto>   list   =   this.managerService.selectManagerForMoom(userinfo.getUserid());
                if(list.size()>0){
                    //  有管理宿舍,不可以禁用

                    return  new MsgDto(false,"该宿管有管理的宿舍,不可禁用");
                }else{

                    //将该宿管用户禁用
                    this.userinfoService.updateById(userinfo);

                    return  new MsgDto(true,"可禁用");
                }


            }



        }else{

                    this.userinfoService.updateById(userinfo);

                    return  new MsgDto(true,"已启用");
                }



            }














    //添加新用户
    @PostMapping("addUser")
    public MsgDto addUser(Userinfo userinfo,String role){

        //第一步，向用户表添加一条数据
        this.userinfoService.save(userinfo);


        System.out.println(role);

        //第二步  判断用户的身份? 如果是学生就向学生表添加一条数据！ 如果是宿管就向宿管表添加一条数据！
        if(role.equals("学生")){

            Student  student  =    new Student(null,userinfo.getUserid(),null,null,"否");
            this.studentService.save(student);


            UserRole   userRole  =  new UserRole(null,userinfo.getUserid(),3);

            //第三步 ，向 用户角色表 添加一条数据
            this.userRoleService.save(userRole);


        }else{

            Manager  manager  =    new Manager(null,userinfo.getUserid(),"在职");
            this.managerService.save(manager);

            UserRole   userRole  =  new UserRole(null,userinfo.getUserid(),2);
//第三步 ，向 用户角色表 添加一条数据
            this.userRoleService.save(userRole);
        }

        return   new MsgDto(true,"添加用户及子身份成功");

    }





    //实现分页查询所有用户(带 用户名模糊查询)
    @PostMapping("selectUser")
    public Page<Userinfo> selectUser(UserInfoDto userinfodto){

        QueryWrapper queryWrapper   =   new QueryWrapper();


        queryWrapper.gt("userId",1);
        queryWrapper.like("username",userinfodto.getUsername());


        Page<Userinfo> page=new Page<>(userinfodto.getCurrent(),userinfodto.getSize());
        this.userinfoService.page(page,queryWrapper);
        return   page;


    }








    // 用户登录
    @PostMapping("login")
    public MsgDto login(String username,String password, HttpSession httpSession){


        List<LoginDto> userinfolist   =   this.loginService.login(username,password);


        if(userinfolist.size()==0){
            System.out.println("登录失败");
            return   new MsgDto(false,"登录失败",null);
        }else{
            System.out.println("登录成功");
          userinfolist.forEach(System.out::println);
            return   new MsgDto(true,"登录成功",userinfolist);
        }

    }

    //修改个人资料
    @RequestMapping("changeInfo")
    public MsgDto changeInfo( Userinfo userinfo){
        this.userinfoService.updateById(userinfo);

        //修改后重新查询用户
        List<LoginDto> updatesellist = this.loginService.updateSelect(userinfo.getUserid());



        return new MsgDto(true,"修改成功",updatesellist);
    }





    //后端清除登录信息
    @PostMapping("loginout")
    public MsgDto logout(HttpSession session, SessionStatus sessionStatus) {

        session.invalidate();
        sessionStatus.isComplete();

        System.out.println("退出登录");
        return   new MsgDto(true,"退出登录",null);


    }

    //文件上传
    @RequestMapping("uploadImg")
    public MsgDto uploadImg(String title, MultipartFile img, HttpSession session) throws IOException {
        //保存到当前工程目录下
        if(img!=null && img.getSize()>0){
            //1.得到发布之后的绝对路径
            String realpath = "C:\\uploadImg";

            //2.根据当前日期创建文件夹(如果存在，忽略)
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String dir = sdf.format(new Date());
            File file = new File(realpath+"/"+dir);
            if(!file.exists()){
                file.mkdir();
            }




            String oldName = img.getOriginalFilename();
            //3.产生一个文件名(上传的文件名)
            //随机文件名
            // String fileName = UUID.randomUUID()+oldName.substring(oldName.lastIndexOf("."));

            String fileName = UUID.randomUUID()+oldName.substring(oldName.lastIndexOf("."));

            String path = realpath+"/"+dir+"/"+fileName;

            //实现文件的复制
            img.transferTo(new File(path));

            String url = "/"+dir+"/"+fileName;
            System.out.println(url);

            return new MsgDto(true,"上传成功",url);

        }

        return new MsgDto(false,"上传失败");
    }







}
